package org.ssp.test;

import java.security.GeneralSecurityException;
import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import org.ssp.pojo.Mail;

import com.sun.mail.util.MailSSLSocketFactory;

/*
 * 邮件工具类
 */
public class MailUtil {
	
	//创建适用于qq服务器的session对象
	public static Session getSession1(){
		Properties prop=new Properties();
		prop.setProperty("mail.host", "smtp.qq.com");
		prop.setProperty("mail.transport.protocol", "smtp");
		prop.setProperty("mail.smtp.auth", "true");
		MailSSLSocketFactory sf=null;
		//ssl加密
		try {
			sf = new MailSSLSocketFactory();
			sf.setTrustAllHosts(true);

		} catch (GeneralSecurityException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		prop.put("mail.smtp.ssl.enable", "true");
		prop.put("mail.smtp.ssl.socketFactory", sf);
		return Session.getInstance(prop);
		
	}
	//创建适用于163服务器的session对象
	public static Session getSession2(){
		Properties prop=new Properties();
		prop.setProperty("mail.host", "smtp.qq.com");
		prop.setProperty("mail.transport.protocol", "smtp");
		prop.setProperty("mail.smtp.auth", "true");
		return Session.getInstance(prop);
	}
	//创建简单邮件
	public static MimeMessage createMail(Session session,Mail mail){
		MimeMessage message=new MimeMessage(session);
		try {
			message.setFrom(new InternetAddress(mail.getFrom()));
			new InternetAddress();
			InternetAddress[] adds=InternetAddress.parse(getAddress(mail.getTo()));
 			message.setRecipients(Message.RecipientType.TO, adds);
 			message.setSubject(mail.getSubject());
 			message.setContent(mail.getContent(), "text/html;charset=utf-8");
 			
		} catch (AddressException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		} catch (MessagingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
		
		return message;
	}
	//创建带内嵌图片的邮件
	public static MimeMessage createImageMail(Session session){
		return null;
		
	}
	//创建带附件的邮件
	public static MimeMessage createAttachMail(Session session){
		return null;
		
	}
	//创建带内嵌图片和附件的邮件
	public static MimeMessage createMixedMai(Session session){
		return null;
		
	}
	
   //考虑给多人发送，构造发送地址:(add1;add2;add3;)
   public static String getAddress(String[] addstr){
	   StringBuffer strbf=new StringBuffer();
	   for(int i=0;i<addstr.length;i++){
		   strbf.append(addstr[i]);
		   strbf.append(",");//注意是,不是;
	   }
	   return strbf.toString();
   }

}

